package org.angelica.common.query;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.CaseFormat;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

/**
 * 列表查询基础类
 * 封装分页和排序条件
 * @author aizhimin
 */
@Setter
public class BaseQuery<T> {

    private static final String SORT_ASC = "ascend";
    private static final String SORT_DESC = "descend";
    /**
     * 默认第一页
     */
    public int currentPage = 1;
    /**
     * 默认每页10条
     */
    public int pageSize = 10;
    /**
     * 排序
     */
    public String sorter;

    public Page<T> buildPage(){
        Page<T> pageQuery = new Page(currentPage,pageSize);
        //设置排序字段：sorter=status-desc
        if(StringUtils.isNotBlank(sorter)){
            String[] sorterArr = sorter.split("-");
            if(SORT_ASC.equals(sorterArr[1])){
                //将驼峰命名转换成下划线命名
                String ascField = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, sorterArr[0]);
                pageQuery.addOrder(OrderItem.asc(ascField));
            }else if(SORT_DESC.equals(sorterArr[1])){
                //将驼峰命名转换成下划线命名
                String descField = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, sorterArr[0]);
                pageQuery.addOrder(OrderItem.desc(descField));
            }
        }
        return pageQuery;
    }

}
